'use strict';

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin');
const utils = require('../utils');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const LoadablePlugin = require('@loadable/webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
/**
 *
 * @param {object} data
 * @param {*} data.buildPath
 * @param {*} data.mainPath
 * @param {*} data.moduleName
 * @param {*} data.gitLoacl
 * @param {*} data.ctx
 */
module.exports = function (data, config) {
  return {
    entry: path.join(data.buildPath, 'src', 'index.js'),
    output: {
      path: path.join(data.buildPath, 'dist'),
      filename: 'js/[name].[hash:8].js',
      chunkFilename: 'js/[name].[hash:8].chunk.js',
    },
    optimization: {
      minimize: true,
      minimizer: [new TerserPlugin({
        exclude: /\/excludes/,
      }), new OptimizeCssPlugin()],
    },
    mode: 'production',
    stats: { children: false, warnings: false },
    resolve: {
      extensions: [
        '.js',
        '.tsx',
        '.json',
      ],
      modules: [
        'node_modules',
        path.join(data.rootPath, 'node_modules'),
        path.join(utils.rootPath, 'node_modules'),
      ],
      alias: {
        '@': path.join(data.rootPath),
      },
    },
    resolveLoader: {
      modules: [
        'node_modules',
        path.join(data.rootPath, 'node_modules'),
        path.join(utils.rootPath, 'node_modules'),
      ],
    },
    externals: {
      vue: 'Vue',
    },
    module: {
      rules: [
        utils.getImageLoader(),
        {
          test: /\.css$/,
          use: [
            {
              loader: require('mini-css-extract-plugin').loader,
              options: {
                hmr: false,
                publicPath: '../',
              },
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: false,
              }
            },
            {
              loader: 'postcss-loader',
              options: utils.postcssOptions(false, {postcssConfig:{
                plugins: {
                  autoprefixer: {},
                  'postcss-px-to-viewport': {
                    unitToConvert: 'px',
                    viewportWidth: 375,
                    unitPrecision: 5,
                    propList: ['*'],
                    viewportUnit: 'vw',
                    fontViewportUnit: 'vw',
                    selectorBlackList: [],
                    minPixelValue: 1,
                    mediaQuery: false,
                    replace: true,
                    exclude: undefined,
                    include: undefined,
                    landscape: false,
                    landscapeUnit: 'vw',
                    landscapeWidth: 568
                  }
                }}
              })
            },
          ]
        },
        {
          test: /\.less$/,
          use: [
            {
              loader: require('mini-css-extract-plugin').loader,
              options: {
                hmr: false,
                publicPath: '../',
              },
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: false,
              }
            },
            {
              loader: 'postcss-loader',
              options: utils.postcssOptions(false, {postcssConfig:{
                plugins: {
                  autoprefixer: {},
                  'postcss-px-to-viewport': {
                    unitToConvert: 'px',
                    viewportWidth: 375,
                    unitPrecision: 5,
                    propList: ['*'],
                    viewportUnit: 'vw',
                    fontViewportUnit: 'vw',
                    selectorBlackList: [],
                    minPixelValue: 1,
                    mediaQuery: false,
                    replace: true,
                    exclude: undefined,
                    include: undefined,
                    landscape: false,
                    landscapeUnit: 'vw',
                    landscapeWidth: 568
                  }
                }}
              })
              
            },
            {
              loader: 'less-loader',
              options: {
                sourceMap: false,
              },
            },
          ]
        },
        utils.getMediaLoader(),
        utils.getFontsLoader(),
        utils.getSvgLoader(),
        {
          test: /\.jsx?$/,
          exclude: /(node_modules|bower_components)/,
          use: ['cache-loader', {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              cwd: utils.rootPath,
              "presets": [["@babel/env", {
                "targets": {
                  // The % refers to the global coverage of users from browserslist
                  "browsers": ["> 1%", "last 2 versions", "not dead"]
                }
              }]],
              "plugins": ["transform-vue-jsx", "@babel/plugin-transform-runtime", [
                'import',
                {
                  libraryName: '@xt/bear',
                  libraryDirectory: 'lib',
                  camel2DashComponentName: true, // 是否需要驼峰转短线
                  camel2UnderlineComponentName: false // 是否需要驼峰转下划线
                },
                '@xt/bear'
              ],
                [
                  'import',
                  {
                    libraryName: 'lodash',
                    libraryDirectory: '',
                    camel2DashComponentName: false, // 是否需要驼峰转短线
                    camel2UnderlineComponentName: false // 是否需要驼峰转下划线
                  },
                  'lodash'
                ]]
            }
          }]
        },
        {
          test: /\.tsx$/,
          exclude: /(node_modules|bower_components)/,
          use: [
            'cache-loader',
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true,
                cwd: utils.rootPath,
                "presets": [["@babel/env", {
                  "targets": {
                    // The % refers to the global coverage of users from browserslist
                    "browsers": ["> 1%", "last 2 versions", "not dead"]
                  }
                }]],
                "plugins": ["transform-vue-jsx", "@babel/plugin-transform-runtime", [
                  'import',
                  {
                    libraryName: '@xt/bear',
                    libraryDirectory: 'lib',
                    camel2DashComponentName: true, // 是否需要驼峰转短线
                    camel2UnderlineComponentName: false // 是否需要驼峰转下划线
                  },
                  '@xt/bear'
                ],
                  [
                    'import',
                    {
                      libraryName: 'lodash',
                      libraryDirectory: '',
                      camel2DashComponentName: false, // 是否需要驼峰转短线
                      camel2UnderlineComponentName: false // 是否需要驼峰转下划线
                    },
                    'lodash'
                  ]]
              }
            },
            {
              loader: 'ts-loader',
              options: {
                transpileOnly: true,
                happyPackMode: true,
                context: data.rootPath,
                configFile: require.resolve('../../../cube/tsconfig')
              },
            },]
        },
      ],
    },
    plugins: [
      new CleanWebpackPlugin(),
      new ErrorOverlayPlugin(),
      new LoadablePlugin({
        filename: 'loadable-stats.prod.json',
        writeToDisk: {
          filename: data.buildPath,
        },
      }),
      new MiniCssExtractPlugin({
        filename: 'style/[name].[hash:8].css',
      }),
      // new PreloadWebpackPlugin({
      //   rel: 'preload',
      //   include: 'initial',
      // }),
      new HtmlWebpackPlugin({
        template: path.join(data.buildPath, 'src', 'index.html'),
        filename: 'index.html',
        inject: 'body',
        title: '喜团',
      }),

      new webpack.LoaderOptionsPlugin({
        debug: true,
        minimize: false,
        options: {
          context: path.join(data.rootPath),
        },
      }),
    ],
  };
};
